import $ from "jquery"
import Vue from "vue"
import { OBJECT } from "oneutil"
import OneKit from "../weixin2vue/OneKit"
export default function (ONEKIT_JSON, ONEKIT_FIELD, ONEKIT_SJS, wx_object) {

  function _init_data (THIS) {
    let temp_data = wx_object.data ? OBJECT.clone(wx_object.data) : {}
    // const onekit_dataKeys = Object.keys(temp_data)
    for (const dataKey of ONEKIT_FIELD) {
      if( wx_object[dataKey]){
        continue;
      }
      const keyPath = dataKey.split('.')
      // console.log(keyPath)
      var temp = temp_data
      for (var k = 0; k < keyPath.length; k++) {
        const key = keyPath[k]
        const key2 = keyPath[k + 1]
        if (temp[key] != null) {
          if (key2 == "length") {
            temp[key] = [];
            break
          } else {
            temp = temp[key]
          }
        } else {
          temp[key] = "";
        }

      }
      //  console.log(temp_data)
    }
    THIS.onekit_data = temp_data
    return temp_data
  }


  function initMembers (instance, isPrev) {
    if (wx_object) {
      for (let key of Object.keys(wx_object)) {
        let obj = wx_object[key];
        switch (key) {
          case "data":
          case "onLoad":
          case "onUnload":
          case "onReady":
          case "onShow":
          case "onHide":
            break;
          case "onShareAppMessage":
            break;
            case "methods":
              if(instance.methods){
              instance.methods = Object.assign(instance.methods,obj)
              }
              break
          default:
            if (isPrev) {
              if (typeof (obj) === "function") {
                if (!instance[key]) {
                  instance.methods[key] = obj;
                }
              }
            } else {
              if (typeof (obj) !== "function") {
                //instance[key] = obj ? OBJECT.clone(obj) : obj
                instance[key] = obj
              }
            }
            break;
        }
      }
    }
  }
  let vue_object = {
    data () {
      return this.data || _init_data(this)
    },
    created () {
      window.CURRENT = this
      initMembers(this, false);
      //1
      this.onekit_render_begin = new Date().getTime()
      window.onekit_performances.push({
        duration: this.onekit_render_begin - window.onekit_rout_begin,
        entryType: "navigation",
        name: "route",
        navigationStart: window.onekit_rout_begin,
        navigationType: "navigateTo",
        path: this.$route.query,
        startTime: this.onekit_render_begin
      })
    },
    destroyed () {
      if (wx_object["onUnload"]) {
        wx_object["onUnload"].call(this);
      }
    },
    mounted () {

      const APP_JSON = window.APP_JSON;
      const query = this.$route.query
      /////////////////////////////////////////

      $(function () {
        $("div").contextmenu(function () {
          const e = e || window.event;
          if (e && e.preventDefault) {
            e.preventDefault();
          } else {
            window.event.returnValue = false;
          }
          window.parent.postMessage(this.outerText, '*')
        })
      });
      //
      // top.postMessage('hello', '*');
      /////////////////////////////////////////
      /////////////////////////////////////////
      this.data = _init_data(this)
      /////////////
      this.onekit_script_begin = new Date().getTime()
      window.onekit_performances.push({
        duration: this.onekit_script_begin - this.onekit_render_begin,
        entryType: "render",
        name: "firstRender",
        path: this.$route.query,
        startTime: this.onekit_render_begin
      })
      if (wx_object["onLoad"]) {
        this.eventChannelID = query.eventChannelID
        delete query["eventChannelID"]
        wx_object["onLoad"].call(this, query);
      }

      //////////////
      let WINDOW_JSON = {
        navigationBarBackgroundColor: "#000000",
        navigationBarTextStyle: "white",
        navigationStyle: "default",
        backgroundColor: "#000000",
        backgroundTextStyle: "dark",
      };
      if (APP_JSON.window) {
        for (let key of Object.keys(APP_JSON.window)) {
          let value = APP_JSON.window[key];
          if (value) {
            WINDOW_JSON[key] = typeof (value) == 'string' && value.startsWith("@") ? OneKit.theme()[value.substr(1)] : value;
          }
        }
      }
      if (typeof (ONEKIT_JSON) != "undefined") {
        for (let key in ONEKIT_JSON) {
          let item = ONEKIT_JSON[key];
          if (!item) {
            continue;
          }
          switch (key) {
            case "backgroundColorTop":
            case "backgroundColorBottom":
            case "enablePullDownRefresh":
            case "onReachBottomDistance":
            case "pageOrientation":
            case "navigationBarTitleText":
              WINDOW_JSON[key] = item
              break;
            case "usingComponents":

              break;
            default:
              throw new Error(key, item)
          }
        }
      }
      this.$emit('updatewindowjson', { WINDOW_JSON });

      if (wx_object["onReady"]) {
        wx_object["onReady"].call(this);
      }
    },
    beforeRouteEnter (to, from, next) {
      window.CURRENT = this
      next(vm => {
        //3
        if (wx_object["onShow"]) {
          wx_object["onShow"].call(vm);
        }
      });
    },
    beforeRouteLeave (to, from, next) {
      next(vm => {
        if (wx_object["onHide"]) {
          wx_object["onHide"].call(vm);
        }
      });
    },
    methods: {
      onekit_handle (name) {
        this[name]();
      },
      animate () {

      },
      setData (data) {
        if (data == null) {
          return
        }
        Object.assign(this.onekit_data, data)
        this.data = this.onekit_data
        this.$nextTick(function () {
          for (let k of Object.keys(data)) {
            const d = data[k]
            this[k] = d
          }
        });
      },
      getOpenerEventChannel () {
        return window.eventChannels[this.eventChannelID];
      }
    },
    components: {}

  };
  console.log(ONEKIT_SJS)
  for (const module of Object.keys(ONEKIT_SJS)) {
    console.log(module)
    const sjs = ONEKIT_SJS[module];
    for (const func of Object.keys(sjs)) {
      console.log(`onekit_${module}_${func}`)
      vue_object.methods[`onekit_${module}_${func}`] = sjs[func]
    }
  }
  initMembers(vue_object, true);
  return vue_object;
}
